package org.example.travel.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.example.travel.common.Result;
import org.example.travel.dto.ScenicActionDTO;
import org.example.travel.dto.ScenicSpotSearchDTO;
import org.example.travel.entity.ScenicSpot;
import org.example.travel.service.ScenicSpotService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/scenic")
@RequiredArgsConstructor
public class ScenicSpotController {

    private final ScenicSpotService scenicSpotService;
    private final StringRedisTemplate redisTemplate;
    private final ObjectMapper objectMapper;

    @GetMapping("/search")
    public Result searchScenicSpots(@ModelAttribute ScenicSpotSearchDTO dto) {
        IPage<ScenicSpot> page = scenicSpotService.search(dto);
        return Result.success(page);
    }

    @PostMapping("/log")
    public Result logScenicAction(@RequestBody ScenicActionDTO dto) {
        scenicSpotService.logAction(dto);
        return Result.success("操作记录成功");
    }

    @GetMapping("/hot")
    public Result getHotScenicFromCache() {
        String json = redisTemplate.opsForValue().get("hot:scenic:top");
        if (!StringUtils.hasText(json)) return Result.success(Collections.emptyList());

        try {
            List<ScenicSpot> list = objectMapper.readValue(json, new TypeReference<>() {});
            return Result.success(list);
        } catch (JsonProcessingException e) {
            return Result.error("热门景点解析失败");
        }
    }
}